<?php


namespace Modules\Common\General\Security\Authorization\Concerns;


use Illuminate\Support\Facades\DB;
use Modules\Common\General\Security\Authorization\Casbin;
use Modules\Common\Models\AdminUser;

trait ManageUser
{
    /**
     * 如果一个用户没有权限，用户通过角色拥有了A权限后，getImplicitUsersForPermission(A)不会查询到该用户，故添加一个虚拟权限
     * @param int $userId
     * @return mixed
     */
    public function addUser(int $userId)
    {
        return Casbin::addPermissionForUser("u$userId", $this->virtualObject, $this->virtualAction);
    }

    public function deleteUser(int $userId)
    {
        return Casbin::deleteUser("u$userId");
    }

    public function deleteUserClearly($userId)
    {
        DB::transaction(function () use ($userId) {
            $this->deleteUser($userId);
            Casbin::deletePermissionsForUser("u$userId");
        });
    }

    protected function usersForPresentation(array $users)
    {
        $arr = [];
        foreach ($users as $user) {
            $userId = substr($user, 1);
            $userName = AdminUser::whereKey($userId)->value('zh_name');
            $arr[] = ['user_id' => $userId, 'user_name' => $userName];
        }
        return $arr;
    }

}
